<?php
namespace app\controller;

use app\BaseController;
use think\validate\ValidateRule;
use think\facade\Session;
use think\facade\Db;
use app\model\Goods as GdsModel;
use app\model\Brands as BdModel;
use app\model\Cls as CsModel;

class Goods extends BaseController
{
    protected $middleware = [
        // 对所有方法有效
        '\app\middleware\NavCheck',
        '\app\middleware\UrlCheck',
        '\app\middleware\LoginCheck',
    ];
    public function index()
    {
        return view();
    }

    public function data()
    {
        $list = GdsModel::alias("gds")
        ->leftJoin("cls","cls.id=gds.cate_id")
        ->leftJoin("brands","brands.id=gds.brand_id")
        ->field('cls.cate_name,gds.*,brands.brand_name')
        ->select();
        $count = GdsModel::count();

        return json([ "code"=>0,"msg"=>"查询成功","count"=>$count,"data"=>$list]);
    }

    public function del($id){
        $user = GdsModel::find($id);
        $res = $user->delete();
        if($res){
            return json(["code"=>0,"msg"=>"删除成功"]);
        }
        return json(["code"=>400,"msg"=>"删除失败"]);
    }

    public function update()
    {
        if($this->request->isPost()){
            $data = $this->request->post();
            var_dump($data);//商品修改还没写完
        }


        $id = $this->request->param("id");
        $goods = GdsModel::where("id",$id)->find();

        $list = BdModel::select();  //查询品牌
        $arr = CsModel::field("id,pid,cate_name")->order("pid","desc")->select();  //查询分类
        $info = $this->record($arr);
        return view("add",["list"=>$list,"info"=>$info,"goods"=>$goods]);
    }

    public function add()
    {
        if($this->request->isPost()){
            $data = $this->request->post();
            $user = new GdsModel();
            $res =  $user->save($data);
            if($res){
                $this->success("添加成功","index");
            }
            $this->error("添加失败,请重试");

        }

        $list = BdModel::select();  //查询品牌

        $arr = CsModel::field("id,pid,cate_name")->order("pid","desc")->select();  //查询分类
        $info = $this->record($arr);

        return view("",["list"=>$list,"info"=>$info]);
    }

    public function record($result=array(),$pid=0,$spac=0,&$newArr=[])
    {
        $spac=$spac+2;
        foreach($result as $key => $value){

            if($value['pid']==$pid){
                $value['cate_name'] = str_repeat('&nbsp;',$spac)."|--".$value['cate_name'];
                $newArr[] = $value;
                //var_dump($key);
                //echo "<br>";
                //var_dump($result[$key]);
                $this->record($result,$value['id'],$spac,$newArr);
            }
        }
        return $newArr;
    }



}
